package 第二周;

/*
 * @author  YxinMiracle
 * @date  2022-04-25 9:47
 * @Gitee: https://gitee.com/yxinmiracle
 */

import java.util.*;

public class 串联所有单词的子串 {

    public Map<String, Integer> wordsMap = new HashMap<>();
    public List<Integer> result = new ArrayList<>();

    public List<Integer> findSubstring(String s, String[] words) {
        // 获取words数组的长度
        int wordsLength = 0;
        for (String word : words) {
            wordsLength += word.length();
            if (wordsMap.containsKey(word)) {
                // 如果map中存在
                Integer count = wordsMap.get(word);
                wordsMap.put(word, ++count);
            } else {
                // 如果map中不存在
                wordsMap.put(word, 1);
            }
        }

        // 遍历s
        // 取出一个个长度为wordsLength的子串
        for (int i = 0; i + wordsLength <= s.length(); i++) {
            if (checkString(s.substring(i, i + wordsLength), words[0].length())) {
                result.add(i);
            }
        }
        return result;
    }

    public boolean checkString(String wantCheckString, Integer wordLength) {
        Map<String, Integer> checkStringMap = new HashMap<>();
        for (int i = 0; i + wordLength <= wantCheckString.length(); i = i + wordLength) {
            String s = wantCheckString.substring(i, i + wordLength);
            if (checkStringMap.containsKey(s)) {
                // 如果map中存在
                Integer count = checkStringMap.get(s);
                checkStringMap.put(s, ++count);
            } else {
                // 如果map中不存在
                checkStringMap.put(s, 1);
            }
        }
        return checkIsTrue(checkStringMap);
    }

    public boolean checkIsTrue(Map<String, Integer> checkStringMap) {
        // wordsMap
        for (Map.Entry<String, Integer> stringIntegerEntry : checkStringMap.entrySet()) {
            if (!wordsMap.containsKey(stringIntegerEntry.getKey())) {
                return false;
            }
            if (!stringIntegerEntry.getValue().equals(wordsMap.get(stringIntegerEntry.getKey()))){
                return false;
            }
        }

        for (Map.Entry<String, Integer> stringIntegerEntry : wordsMap.entrySet()) {
            if (!checkStringMap.containsKey(stringIntegerEntry.getKey())) {
                return false;
            }
            if (!stringIntegerEntry.getValue().equals(checkStringMap.get(stringIntegerEntry.getKey()))){
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String s = "wordgoodgoodgoodbestword";
        String[] words = new String[]{"word", "good", "best", "good"};
        System.out.println(new 串联所有单词的子串().findSubstring(s, words));
    }

}
